//
//  homeImageViewController.m
//  GentlemanAnime
//
//  Created by dlios on 15-7-14.
//  Copyright (c) 2015年 lanou3g.com 蓝欧科技. All rights reserved.
//

#import "homeImageViewController.h"
#import "ImageDetailCollectionViewCell.h"
#import "ImageDetailViewController.h"
#import "ImageShowViewController.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "HTTPTool.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface homeImageViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)UIImageView *headerView;
@property(nonatomic, retain)UIView *detailView;
@property(nonatomic, copy)NSString *headerUrl;
@property(nonatomic, retain)NSArray *picArr;
@property(nonatomic, retain)NSMutableArray *flyPicArr;
@property(nonatomic, retain)UIImageView *upImageView;
@property(nonatomic, retain)UIImageView *downImageView;
@property(nonatomic, retain)ImageDetailCollectionViewCell *selectCell;
@property(nonatomic, retain)MBProgressHUD *HUD;
@property(nonatomic, assign)BOOL isArchiver;
@property(nonatomic, retain)NSMutableArray *imageArr;

@end

@implementation homeImageViewController

- (void)dealloc {
    [[SDImageCache sharedImageCache] clearMemory];
    [_HUD release];
    [_selectCell release];
    [_upImageView release];
    [_downImageView release];
    [_headerUrl release];
    [_picArr release];
    [_collectionView release];
    [_headerView release];
    [_detailView release];
    [_imageArr release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.flyPicArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *titlelebel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    titlelebel.text = self.modeltitle;
    titlelebel.font = [UIFont boldSystemFontOfSize:18];
    titlelebel.textAlignment = NSTextAlignmentCenter;
    titlelebel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titlelebel;
    [titlelebel release];
    
    
    
    // 反归档
    [self fanGuiDang];
    
    // 绘制collectionView
    [self createCollectionView];
    
    // 头图片
    [self createHeaderView];
    
    // 小菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.mode = MBProgressHUDModeIndeterminate;
    self.HUD.color = [UIColor colorWithRed:0.334 green:0.619 blue:1.000 alpha:1.000];
    
    // 网路数据解析
    [self createData];
}

#pragma mark 绘制collectionView
- (void)createCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 设置每个item大小
    flowLayout.itemSize = CGSizeMake((WIDTH - 14) / 3, (WIDTH - 14) / 3);
    // 设置最小行间距
    flowLayout.minimumLineSpacing = 7;
    flowLayout.minimumInteritemSpacing = 7;
    // 设置边距
    flowLayout.sectionInset = UIEdgeInsetsMake(7, 0, 7, 0);
    
    // 创建collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) collectionViewLayout:flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.contentInset = UIEdgeInsetsMake((HEIGHT - 113 ) / 3, 0, 0, 0);
    self.collectionView.contentSize = CGSizeMake(WIDTH, 2 * HEIGHT);
    // 设置代理人
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    // 设置背景颜色
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [flowLayout release];
    [_collectionView release];
    
    // 注册collectionView的item
    [self.collectionView registerClass:[ImageDetailCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
}

#pragma mark 返回item个数的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.picArr.count;
}

#pragma mark 生成item的方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ImageDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    //    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:self.picArr[indexPath.row]]];
    NSString *str = [NSString stringWithFormat:@"%@?imageView2/1/w/%1.0f/h/%1.0f",self.picArr[indexPath.row],(WIDTH - 14) / 3,(WIDTH - 14) / 3];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:str] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        cell.userInteractionEnabled = YES;
    }];
    
    
    return cell;
}

#pragma mark item点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.selectCell = (ImageDetailCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    CGRect oldFrame = self.selectCell.frame;
    
    void (^regainItemBlock)() = ^(){
        self.selectCell.transform = CGAffineTransformScale(self.selectCell.transform, 1 / 3.0, 1 / 3.0);
        self.selectCell.frame = oldFrame;
        self.selectCell.alpha = 1;
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
    };
    
    [UIView animateWithDuration:0.4 animations:^{
        self.selectCell.transform = CGAffineTransformScale(self.selectCell.transform, 3, 3);
        [self.selectCell.superview bringSubviewToFront:self.selectCell];
        self.selectCell.alpha = 0;
    } completion:^(BOOL finished) {
        ImageShowViewController *imageShowVC = [[ImageShowViewController alloc] init];
        imageShowVC.backGroundImage = self.selectCell.picImageView.image;
        imageShowVC.collectionViewOffX = indexPath.row * WIDTH;
        imageShowVC.pirArr = self.picArr;
        imageShowVC.index = indexPath.row;
        imageShowVC.regainItemBlock = regainItemBlock;
        [imageShowVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
        [self presentViewController:imageShowVC animated:YES completion:^{
            
        }];
        [imageShowVC release];
    }];
    
}

#pragma mark 绘制头图片
- (void)createHeaderView {
    UIImageView *backView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -(HEIGHT - 113 ) / 3, WIDTH, (HEIGHT - 113 ) / 3)];
    [self.collectionView addSubview:backView];
    backView.image = [UIImage imageNamed:@"漫图占位图"];
    backView.clipsToBounds = YES;
    [backView release];
    
    self.headerView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, WIDTH, (HEIGHT - 113 ) / 3)];
    self.headerView.contentMode = UIViewContentModeScaleAspectFill;
    [backView addSubview:self.headerView];
    [_headerView release];
    
    // 上下蒙版
    self.upImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, self.headerView.frame.size.height * 2 / 3)];
    self.upImageView.image = [UIImage imageNamed:@"大图蒙板上"];
    [backView addSubview:self.upImageView];
    [_upImageView release];
    self.downImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,self.headerView.frame.size.height / 3, WIDTH, self.headerView.frame.size.height * 2 / 3)];
    self.downImageView.image = [UIImage imageNamed:@"大图蒙板"];
    [backView addSubview:self.downImageView];
    [_downImageView release];
}

#pragma mark 解析数据
- (void)createData {
    NSString *url = [NSString stringWithFormat:@"http://acg.18touch.com/api/imageList/%@?ak=&dk=e566b36fd99f9576285804a58f3e4fe3d4883441&v=1.2",self.Id];
    [HTTPTool get:url body:nil httpResultStyle:JSON success:^(id result) {
        NSDictionary *dic = result;
        
        NSRange range = [(NSString *)dic[@"coverImage"] rangeOfString:@"jpg"];
        if (range.length == 0) {
            range = [(NSString *)dic[@"coverImage"] rangeOfString:@"png"];
            if (range.length == 0) {
                range = [(NSString *)dic[@"coverImage"] rangeOfString:@"JPG"];
                if (range.length == 0) {
                    range = [(NSString *)dic[@"coverImage"] rangeOfString:@"PNG"];
                }
            }
        }
        NSString *str = [(NSString *)dic[@"coverImage"] substringToIndex:range.location + 3];
        self.headerUrl = [NSString stringWithFormat:@"%@?imageView2/1/w/320/h/188",str];
        
        self.picArr = dic[@"images"];
        
        [self.headerView sd_setImageWithURL:[NSURL URLWithString:self.headerUrl] placeholderImage:[UIImage imageNamed:@"zhanweitu2"] animationBlock:^{
            [UIView animateWithDuration:1.5 delay:0.3 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                self.upImageView.frame = CGRectMake(0, 0, WIDTH, self.headerView.frame.size.height / 7);
                self.downImageView.frame = CGRectMake(0,self.headerView.frame.size.height * 6 / 7, WIDTH, self.headerView.frame.size.height / 7);
            } completion:nil];
        }];
        
        // 刷新collectionView
        [self.collectionView reloadData];
        [self.HUD hide:YES];
    } failure:^(NSError *error) {
        
    }];
}



#pragma mark 反归档
- (void)fanGuiDang
{
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
    NSString *sandBoxPath = sandBox[0];
    NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"image.plist"];
    self.imageArr = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
    self.isArchiver = NO;
    if (self.imageArr == nil) {
        self.imageArr = [NSMutableArray array];
    }else{
        for (ImageTableViewModel *image in self.imageArr) {
            if ([image.PicTitle isEqualToString:self.modeltitle]) {
                self.isArchiver = YES;
                break;
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
